/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#include "maya_local.h"
#include "../core/rapidxml/rapidxml_ext.hpp"
#include "../core/rapidxml/rapidxml_print.hpp"
using namespace rapidxml;


const uint SCENE_MESH_FORMAT = GE_MESH_POSITION | GE_MESH_COLOR_0 | GE_MESH_NORMAL | GE_MESH_UV_0 | GE_MESH_JOINT_IND | GE_MESH_JOINT_WEIGHTS;

/*-----------------------------------------------------------------------------
	Maya scene export :
-----------------------------------------------------------------------------*/

//
//	EMSceneExporter::EMSceneExporter
//
EMSceneExporter::EMSceneExporter( void )
{

}

//
//	EMSceneExporter::~EMSceneExporter
//
EMSceneExporter::~EMSceneExporter( void )
{

}


//
//	EMSceneExporter::WriteSceneXML
//
MStatus EMSceneExporter::WriteSceneXML( IPxScene scene, const char *path )
{
	LOGF("Building XML hierarchy...\r\n");
	
	xml_document<>	xdoc;
	xml_node<>		*xscene			=	xdoc.allocate_node(node_element, "scene");
	
	xdoc.append_node( xscene );	
	
	scene->WriteXML( xscene );
	
	LOGF("Writing XML file...\r\n");

	//	Write xml file :
	try {
		ofstream	out_file;
		out_file.open(path);
		out_file << xdoc;
		out_file.close();
		
	} catch (exception &e) {
		MGlobal::displayWarning((const char*)va("Cann`t write '%s'", path));
		MGlobal::displayWarning(e.what());
		return MStatus::kFailure;
	}
	
	return MS::kSuccess;
}


//
//	EMSceneExporter::writer
//
MStatus EMSceneExporter::writer( const MFileObject& file, const MString& optionsString, MPxFileTranslator::FileAccessMode mode )
{
	if (mode == MPxFileTranslator::kExportActiveAccessMode) {
		MGlobal::displayWarning("Level exporter must work with entire scene");
		return MStatus::kFailure;
	}
	
	IPxScene	scene	=	ge()->CreateScene();

	string	path = file.fullName().asChar();
	LOG_SPLIT(va("Level export : %s", path.c_str()));
	
		//
		//	Parse hierarchy :
		//
		//	get root path :
		MItDag		dag_iter(MItDag::kDepthFirst, MFn::kTransform);
		MFnDagNode	root_node( dag_iter.root() );
		MDagPath	dag_path;
		MAYA_CALL( root_node.getPath( dag_path ) );

		LOGF("Parsing DAG hierarchy...\r\n");
		MAYA_CALL( ParseHierarchy( scene->Root(), dag_path, 0 ) );		


		//
		//	Preprocess level and write XML :
		//
		WriteSceneXML( scene, path.c_str() );
		//level->Process();
		//level->WriteXML(path.c_str());
		

	LOG_SPLIT("");

	return MStatus::kSuccess;
}


//
//	EMLevelExporter::ParseHierarchy
//
MStatus EMSceneExporter::ParseHierarchy( IPxSceneNode scene_node, MDagPath node_path, uint depth )
{
	MStatus status;
	
	MObject	node = node_path.node();
	
	EMatrix scale;

	//
	//	Setup transformation for current node :
	//	NOTE : root node does not have transform
	//	
	if (depth!=0) {
		//	check transform node :	
		ASSERT( node.hasFn(MFn::kTransform) );

		ParseTransform( scene_node, node, scale );
	} 
	
	//
	//	Set name :
	//	
	MFnDagNode dag_node(node);
	scene_node->SetName( dag_node.name().asChar() );

	//
	//	Get affector :
	//	
	scene_node->SetAffector( Maya_ReadString(node, "affector", MString("")).asChar() );
	
	//
	//	Iterate over all child :	
	//
	for (uint i=0; i<node_path.childCount(); i++) 
	{
		MObject		child		=	node_path.child(i);
		MDagPath	child_path	=	node_path;
		child_path.push( child );	// extend path to child

		//	skip these objects :
		if (child_path.fullPathName()=="|groundPlane_transform"	)	continue;
		if (child_path.fullPathName()=="|Manipulator1"			)	continue;
		if (child_path.fullPathName()=="|UniversalManip"		)	continue;
		if (child_path.fullPathName()=="|CubeCompass"			)	continue;
		if (child_path.fullPathName()=="|persp"					)	continue;
		if (child_path.fullPathName()=="|top"					)	continue;
		if (child_path.fullPathName()=="|front"					)	continue;
		if (child_path.fullPathName()=="|side"					)	continue;

		//		
		//	Child is a locator, add entity desc :
		//
		if (child.hasFn(MFn::kLocator)) {
			scene_node->SetClass("locator");
			continue;
		}

		if (child.hasFn(MFn::kCamera)) {
			scene_node->SetClass("camera");
			continue;
		}

		if (child.hasFn(MFn::kLight)) {
			scene_node->SetClass("light");
			ParseLight( scene_node, child );
			continue;
		}

		//		
		//	Child is a mesh :
		//
		if (child.hasFn(MFn::kMesh)) {
			MFnDagNode dag_mesh(child);
			//	skip intermediate meshes, such as bool operands etc.
			if (dag_mesh.isIntermediateObject()) {
				continue;
			}
			
			scene_node->SetClass("mesh");
			scene_node->SetMesh( ge()->CreateTriMesh( SCENE_MESH_FORMAT ) );

			MAYA_CALL( ParseMesh( scene_node->GetMesh(), child, child_path ) );

			scene_node->GetMesh()->Transform( scale );
			
			continue;
		}

		if (child.hasFn(MFn::kJoint)) {
			continue;
		}
		
		//
		//	Child is a transform node, 
		//	continue recursive descending :
		//
		if (child.hasFn(MFn::kTransform)) 
		{
			IPxSceneNode	scene_child_node = ge()->CreateSceneNode();
			scene_node->AttachChild(scene_child_node);
		
			MAYA_CALL( ParseHierarchy(scene_child_node, child_path, depth+1) );
			continue;
		}

	}

	return MS::kSuccess;
}


//
//	EMSceneExporter::ParseLight
//
MStatus EMSceneExporter::ParseLight( IPxSceneNode scene_node, MObject &obj )
{
	if (obj.hasFn(MFn::kPointLight)) {
		MFnPointLight	omni_light(obj);
		
		scene_node->AddAffector( "-shape omni");
		scene_node->AddAffector( va("-intensity %g", omni_light.intensity() ) );
		scene_node->AddAffector( va("-color \"%g %g %g\"", omni_light.color().r, omni_light.color().g, omni_light.color().b ) );
		if (omni_light.useDepthMapShadows() || omni_light.useRayTraceShadows()) {
			scene_node->AddAffector("-use_shadows");
		}
	}
	
	if (obj.hasFn(MFn::kDirectionalLight)) {
		MFnDirectionalLight	dir_light(obj);
		
		scene_node->AddAffector( "-shape direct");
		scene_node->AddAffector( va("-intensity %g", dir_light.intensity() ) );
		scene_node->AddAffector( va("-color \"%g %g %g\"", dir_light.color().r, dir_light.color().g, dir_light.color().b ) );
		if (dir_light.useDepthMapShadows() || dir_light.useRayTraceShadows()) {
			scene_node->AddAffector("-use_shadows");
		}
	}
	
	if (obj.hasFn(MFn::kSpotLight)) {
		MFnSpotLight	spot_light(obj);
		
		scene_node->AddAffector( "-shape spot");
		scene_node->AddAffector( va("-intensity %g", spot_light.intensity() ) );
		scene_node->AddAffector( va("-color \"%g %g %g\"", spot_light.color().r, spot_light.color().g, spot_light.color().b ) );
		if (spot_light.useDepthMapShadows() || spot_light.useRayTraceShadows()) {
			scene_node->AddAffector("-use_shadows");
		}
		scene_node->AddAffector( va("-spot_angle %g", spot_light.coneAngle() ) );
	}
	
	return MS::kSuccess;
}
